import requests
from pyquery import PyQuery
import json
import os

if __name__ == '__main__':
    # 获取圣遗物链接列表
    response = requests.request(
        url="https://api-static.mihoyo.com/common/blackboard/ys_obc/v1/home/content/list?app_sn=ys_obc&channel_id=189"
        , method="get")
    jsonText = json.loads(response.text)

    content_ids = []  # 一个网址拼上content_id就能到达圣遗物的页面

    for i in jsonText["data"]["list"][0]["children"][2]["list"]:
        content_ids.append(i["content_id"])

    # 获取圣遗物详细信息与圣遗物图片
    for content_id in content_ids:
        response = requests.request(
            url="https://api-static.mihoyo.com/common/blackboard/ys_obc/v1/content/info?app_sn=ys_obc&content_id="
                + str(content_id),
            method="get")
        html = PyQuery(json.loads(response.text)["data"]["content"]["contents"][0]["text"])

        head = "images/圣遗物/" + html.children("div:nth-child(1)")("h2").text()  # 这套圣遗物的名字//后续会作为文件夹名字
        print(head)
        # 创建一个名字为这个圣遗物名字的目录
        try:
            os.mkdir(head)
        except BaseException as e:
            pass

        # 保存两件套效果到对应目录下的两件套.txt
        with open(head + "/两件套.txt", 'w', encoding="utf-8") as txt:
            txt.write(html.children("div:nth-child(1)")("table")("tbody")
                      .children("tr:nth-child(3)").children("td:nth-child(2)").text())

        # 保存两件套效果到对应目录下的两件套.txt
        with open(head + "/四件套.txt", 'w', encoding="utf-8") as txt:
            txt.write(html.children("div:nth-child(1)")("table")("tbody")
                      .children("tr:nth-child(4)").children("td:nth-child(2)").text())

        # 保存圣遗物图片到对应目录下
        relics = []
        for i in html.children("div:nth-child(n+2)").items():
            relics.append(i)

        relics.remove(relics[-1])

        for i in relics:
            title = i(".title").text()
            relic_type = i("tbody").children("tr:nth-child(1)")("label").text()
            src = i("img").attr("src")
            picture = requests.request(url=src, method="get")
            with open(head + "/" + relic_type + title + ".png", 'wb') as png:
                png.write(picture.content)
